import React, { Component } from 'react';
import PropTypes from "prop-types";
import {
    Text,
    StyleSheet,
} from 'react-native';

import color from '../../config/theme/standard/color'
import fonts from '../../config/theme/standard/fonts'
import Util from '../../config/util'


export default class TextElement extends Component{

    constructor(props) {
        super(props);
        this.state={
            style:this.setStyle(this.props.customStyle),
            type:this.props.type,
            align:this.props.align
        }
    }
    setNativeProps (nativeProps) {
        this._root.setNativeProps(nativeProps);
    }

    setStyle=(style)=>{
        let textStyle=[styles.textPublic,styles["text"+Util.firstUpperCase(this.props.type)],styles["text"+Util.firstUpperCase(this.props.align)]]

        if(style instanceof Array){
            textStyle=textStyle.concat(style)
        }else{
            textStyle.push(style);
        }
        return textStyle
    }

    // componentWillReceiveProps(nextProps){
    //     this.setState({style:this.setStyle(nextProps.customStyle)})
    // }

    static getDerivedStateFromProps(nextProps, prevState) {
        if ('customStyle' in nextProps) {
            let textStyle=[styles.textPublic,styles["text"+Util.firstUpperCase(prevState.type)],styles["text"+Util.firstUpperCase(prevState.align)]]

            if(nextProps.customStyle instanceof Array){
                textStyle=textStyle.concat(nextProps.customStyle)
            }else{
                textStyle.push(nextProps.customStyle );
            }
            return {
                style: textStyle
            };
        }
        return null;
    }
    
    render(){

        return(
            <Text style={this.state.style} allowFontScaling={false} numberOfLines={this.props.numberOfLines} ref={component => this._root = component}>
                {this.props.text}
            </Text>
        );
    }
}

TextElement.propTypes={
    text:PropTypes.string.isRequired,
    type:PropTypes.oneOf(['normal','title']),
    backgroundColor:PropTypes.string,
    color:PropTypes.string,
    size:PropTypes.number,
    align:PropTypes.oneOf(['left','center','right']),
    // customStyle:PropTypes.object
    customStyle:PropTypes.oneOfType([
        PropTypes.arrayOf(Text.propTypes.style),
        Text.propTypes.style
    ]),
    numberOfLines: PropTypes.number
}

TextElement.defaultProps = {
    type:'normal',
    backgroundColor:color.background,
    color:color.normal,
    size:fonts.fontSize,
    align:'left'
};


const styles=StyleSheet.create({
    textPublic:{
        color:color.title
    },
    textRight:{
        paddingRight:8,
        textAlign:'right'
    },
    textCenter:{
        textAlign:'center'
    },
    textLeft:{
        textAlign:'left'
    },
    textNormal:{
        fontSize:fonts.titleFontSize
    },
    textTitle:{
        fontSize:fonts.titleFontSize,
        fontWeight: 'bold',
    }

})
